package com.business_clean.app.uitl.appupdate;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.network.NetUrl;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.uitl.SignKt;
import com.business_clean.app.uitl.appupdate.update.AllDialogShowStrategy;
import com.business_clean.app.uitl.appupdate.update.MyFileChecker;
import com.business_clean.app.uitl.appupdate.update.MyInstallNotifier;
import com.business_clean.app.uitl.appupdate.update.MyUpdateChecker;
import com.business_clean.app.uitl.appupdate.update.MyUpdateNotifier;
import com.business_clean.app.uitl.appupdate.update.NotificationDownloadCreator;
import com.business_clean.app.uitl.appupdate.update.SetingDialogShowStrategy;
import com.business_clean.app.uitl.appupdate.update.ToastCallback;
import com.business_clean.data.mode.appupdate.NewVersionData;
import com.business_clean.data.mode.appupdate.NewVersionInfo;

import org.json.JSONObject;
import org.lzh.framework.updatepluginlib.UpdateBuilder;
import org.lzh.framework.updatepluginlib.UpdateConfig;
import org.lzh.framework.updatepluginlib.base.UpdateParser;
import org.lzh.framework.updatepluginlib.model.CheckEntity;
import org.lzh.framework.updatepluginlib.model.Update;

import java.util.HashMap;
import java.util.Map;

import me.hgj.mvvmhelper.ext.LogExtKt;


public class AppCheckUpdateUtil {
    public static void checkVersionNew(boolean isSetting) {
        createBuilder(isSetting).check();
    }

    @NonNull
    public static UpdateBuilder createBuilder(boolean isSetting) {
        // 配置toast通知的回调
//        builder.setDownloadCallback(callback);
//        builder.setCheckCallback(callback);
//        if (!newConfig.isDefaultSelected()) {
        UpdateBuilder builder = UpdateBuilder.create(createNewConfig());
        builder.setUpdateChecker(new MyUpdateChecker());
        builder.setFileChecker(new MyFileChecker());
        builder.setCheckNotifier(new MyUpdateNotifier());
        builder.setInstallNotifier(new MyInstallNotifier());

//        }
        // 根据各项是否选择使用默认配置进行使用更新。
//        if (!updateWorker.isDefaultSelected()) {
//        builder.setCheckWorker(OkhttpCheckWorker.class);
//        }

//        if (!hasUpdateNotice.isDefaultSelected()) {
//        builder.setCheckNotifier(new NotificationUpdateCreator());
//        }

//        if (!downloadCompleteNotice.isDefaultSelected()) {
//        builder.setInstallNotifier(new NotificationInstallCreator());
//        }

//        if (!fileCreator.isDefaultSelected() && isPermissionGrant) {
//        builder.setFileCreator(new CustomApkFileCreator());
//        }

//        if (!updateStrategy.isDefaultSelected()) {

        if (isSetting) {
            builder.setUpdateStrategy(new SetingDialogShowStrategy());
            builder.setDownloadCallback(new ToastCallback());
            builder.setDownloadNotifier(new NotificationDownloadCreator());
        } else {
            builder.setUpdateStrategy(new AllDialogShowStrategy());
        }

//        builder.setDownloadNotifier(new DefaultDownloadNotifier());
//        }

//        if (!downloadNotice.isDefaultSelected()) {
//        builder.setDownloadNotifier(new NotificationDownloadCreator());
//        }

//        if (!downloadWorker.isDefaultSelected()) {
//        builder.setDownloadWorker(OkhttpDownloadWorker.class);
//        }
        return builder;
    }

    private static UpdateConfig createNewConfig() {
        String xmjz_time = System.currentTimeMillis() / 1000 + "";

        CheckEntity checkEntity = new CheckEntity();
        String url = MMKVHelper.getString(ConstantMMVK.ENVIRONMENT_BASE_URL) + "/" + NetUrl.CHECK_UPDATE_APP;
        checkEntity.setUrl(url);

        Map<String, String> params = new HashMap<>();

        String token = MMKVHelper.getString(ConstantMMVK.TOKEN);
        if (token == null) {
            token = "";
        }
        params.put("xmjz_time", "" + xmjz_time);

        //添加共同的请求头
        String xmjzsign = SignKt.encodeSign(NetUrl.CHECK_UPDATE_APP, token, params);

        Map<String, String> header = new HashMap<>();
        header.put("xmjztoken", token);
        header.put("xmjzsign", xmjzsign);
        header.put("xmjzplatform", "android");
        header.put("xmjzdevice", DeviceUtils.getManufacturer() + DeviceUtils.getModel());
        header.put("xmjzversion", "" + AppUtils.getAppVersionName());
        checkEntity.setHeaders(header);
        checkEntity.setParams(params);


        LogExtKt.logE("------下载更新-url------" + url, "");
        LogExtKt.logE("------下载更新-params------" + params.toString(), "");
        LogExtKt.logE("------下载更新-header------" + header.toString(), "");

        return UpdateConfig.getConfig()
                .setCheckEntity(checkEntity)
                .setUpdateParser(new UpdateParser() {
                    @Override
                    public org.lzh.framework.updatepluginlib.model.Update parse(String response) throws Exception {
                        // TODO 此处的response数据为上方检查更新接口所返回回来的数据。
                        // 需要在此对response数据进行解析，并创建出对应的update实体类数据
                        // 提供给框架内部进行使用
                        LogExtKt.logE("------下载更新-response------" + response, "");

                        JSONObject object = new JSONObject(response);
                        Update update = new Update();

                        NewVersionData data = JSON.parseObject(response, NewVersionData.class);
                        if (data == null) {
                            return null;
                        }
                        NewVersionInfo newVersionInfo = data.getData();
                        // 此apk包的下载地址
                        update.setUpdateUrl(newVersionInfo.getUrl());
                        // 此apk包的版本号
//                        update.setVersionCode(32);
                        // 此apk包的版本名称
                        update.setVersionName(newVersionInfo.getVersion());
                        // 此apk包的更新内容
                        update.setUpdateContent(newVersionInfo.getDesc());
                        // 此apk包是否为强制更新
                        update.setForced("1".equals(newVersionInfo.getUpgrade_demand()));
                        // 是否显示忽略此次版本更新按钮
                        update.setIgnore(object.optBoolean("ignore_able", false));
                        return update;
                    }
                });
    }

    public static int compareVersion(String v1, String v2) {
        if (v1.equals(v2)) {
            return 0;
        }
        String[] version1 = v1.split("\\.");
        String[] version2 = v2.split("\\.");
        int index = 0;
        int minLen = Math.min(version1.length, version2.length);
        long diff = 0;
        while (index < minLen && (diff = Long.parseLong(version1[index]) - Long.parseLong(version2[index])) == 0)
            index++;
        if (diff == 0) {
            for (int i = index; i < version1.length; i++)
                if (Long.parseLong(version1[i]) > 0)
                    return 1;
            for (int i = index; i < version2.length; i++)
                if (Long.parseLong(version2[i]) > 0)
                    return -1;
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }
}
